// Written by Dale J Williams.
// Licensed under MPL 1.1 unless otherwise specified. 
// http://www.mozilla.org/MPL/MPL-1.1.html

package engineDJW.display {
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	
	/**
	 * ...
	 * @author Dale J Williams
	 */
	public class MovieAsset extends Sprite {
		
		private var _asset				:MovieClip;
		private var _animLabel			:String;
		private var _animComplete		:Function;
		private var _playing			:Boolean = true;
		private var _framesThisCycle	:int;
		
		public function MovieAsset($asset:MovieClip) {
			_asset = $asset;
			_animLabel = "";
			addChild(_asset);
		}
		
		public function update():void {	
			if (_playing) {
				if (_asset.currentFrame == _asset.totalFrames)
					_asset.gotoAndStop(1);
				else _asset.nextFrame();
				_framesThisCycle++;
			}
			if (_asset.currentLabel != _animLabel) {
				if (_animComplete != null) _animComplete();
				else rewind();
				_asset.gotoAndStop(_animLabel);
			}
		}

		public function playAnimation($animName:String, $rewind:Boolean=false, $animComplete:Function=null):void {
			animLabel = $animName;
			_playing = true;
			_animComplete = $animComplete;
			if ($rewind) rewind();
		}
		
		public function stopAnimation($rewind:Boolean=false):void {
			_playing = false;
			if ($rewind) rewind();
		}
		
		public function isAtPosition($label:String, $framesThisCycle:int):Boolean {
			return _animLabel == $label && _framesThisCycle == $framesThisCycle;
		}
		
		public function rewind():void {
			_asset.gotoAndStop(_animLabel);
			_framesThisCycle = 0;
		}
		
		public function get animLabel():String { return _animLabel; }
		public function set animLabel(value:String):void {
			_animLabel = value;
		}
		
		public function get asset():MovieClip { return _asset; }
		
		public function get playing():Boolean { return _playing; }		
		public function set playing(value:Boolean):void {
			_playing = value;
		}
		
		public function get framesThisCycle():int { return _framesThisCycle; }		
		
	}

}